package com.example.service.impl;

import com.example.exception.ServiceException;
import com.example.service.RedisService;
import com.example.utils.ResultCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class RedisServiceImpl implements RedisService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 保存数据
    public void save(String key, Object value) {
        redisTemplate.opsForValue().set(key, value, 10, TimeUnit.MINUTES);  // 设置数据的有效期为10分钟
    }

    @Override
    public void save(String key, Object value, int minute) {
        redisTemplate.opsForValue().set(key, value, minute, TimeUnit.MINUTES);
    }

    // 获取数据
    @Cacheable(value = "myCache", key = "#key")
    public Object get(String key) throws ServiceException {
        Object o = redisTemplate.opsForValue().get(key);
        if (o == null) {
            throw new ServiceException(ResultCodeUtil.DATA_ERROR, "redis获取失败");
        }
        return o;
    }

    // 删除数据
    public void delete(String key) {
        redisTemplate.delete(key);
    }

    public void deleteAll() {
        Set<String> keys = redisTemplate.keys("*");
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }
    }
}